
<template>

    <!--    <el-input v-model="title"  class="input-with-select" :disabled="true">-->
    <!--        <template #append>-->
    <!--            <el-button :icon="el-icon-search" @click="toShow()">选择</el-button>-->
    <!--        </template>-->
    <!--    </el-input>-->

    <div class="select" v-show="isHideUserSelected" >
        <el-tag closable
                :disable-transitions="true"
                v-for="tag in selectedDataItems"
                :key="tag.index"
                @close="handleCloseUser(tag)"
        >
            {{ tag.nickName }}
        </el-tag>
        <el-button icon="el-icon-plus" circle class="new-tag" v-show="isDo" size="small" @click="toShow" />
        <el-button style="margin-left: 10px" v-if="selectedDataItems && selectedDataItems.length>0"   v-show="isDo" @click="handleClearTag">清空</el-button>

    </div>



    <el-dialog title="用户选择" v-model="isShow" class="userSelectDialog"  append-to-body>
        <el-container style="height: 600px">
            <el-aside width="200px" class="userSelectDiv1" height="600px" >
              <div>是否包含下级:
                <el-switch v-model="column.onlyOrg" >
                </el-switch>
              </div>
                <avue-tree ref="tree" :option="treeOption"
                           :data="treeData"
                           @node-click="nodeClickTree"
                ></avue-tree>
            </el-aside>
            <el-main height="500px" class="userSelectDiv2">
                <avue-crud
                        v-model="form"
                        ref="crud"
                        v-model:search="searchForm"
                        v-model:page="page"
                        :option="option"
                        :data="tableData"
                        v-bind="bindVal"
                        v-on="onEvent"
                        @current-row-change="handleCurrentRowChange"
                        @selection-change="selectionChange"
                >
                    <template #menu="{size,row,index}">
                        <el-button v-if="showSelectedBtn" link type="primary"  size="small" icon="el-icon-lock" @click="selectionClick(row)">选择</el-button>
                    </template>

                </avue-crud>

            </el-main>

            <div class="selected-user" >


                <div>
                    <span>已选择的用户：</span>
                    <div style="height: 550px;overflow-y:auto">
                        <el-tag class="el-tag-line"  v-for="d in selectedDataItems"

                        >{{d.nickName}}</el-tag>
                    </div>
                </div>

                <div>
                    <el-button type="primary" @click="handleSubmit">确定</el-button>
                    <el-button type="primary" @click="isShow=false">取消</el-button>
                </div>
            </div>


        </el-container>
    </el-dialog>
</template>

<script>
    import {fetchOrgTree,fetchRoleList,getUsersByids} from '@/framework-core/api/user.js';
    import { convertDic} from '@/framework-core/utils/util'
    import crud from "@/framework-core/mixins/crud";
    import _ from 'lodash'
    export default {
        name: 'userChoose',
        props: ['column','modelValue'],
        inject: ['getViewFormData'],
        mixins: [crud],
        data() {
            return {
                pageConfig:{"url":"sys/user"},
                isShow:false,
                multiple:false,
                myUserType:"",
                form: {},
                tableData: [],
                searchForm:{},
                selectedDataItems:[],
                selectedKey:'',
                option:
                    {
                        border: true,
                        index: true,
                        indexLabel: '#',
                        stripe: true,
                        menuAlign: 'center',
                        grid: window.isMobile,
                        editBtn: false,
                        delBtn: false,
                        addBtn: false,
                        reserveSelection: true,
                        selection:this.multiple,
                        highlightCurrentRow:!this.multiple,
                        gridSpan: 24,
                        searchMenuSpan: 6,
                        align: 'center',
                        menu:  window.isMobile,
                        searchEnter: true,
                        column: [
                            {
                                type: "input",
                                label: '姓名',
                                prop: 'nickName',
                                fixed: true,
                                search: true,
                                span: 24,
                            },
                            {
                                type: 'input',
                                label: '手机号',
                                prop: 'phone',
                                search: true,
                                span: 24,
                            },
                            {
                                type: 'select',
                                label: '性别',
                                prop: 'sex',
                                sortable: "custom",
                                "span": 12,
                                dicCode: "sex",
                                'search': false,
                            },
                            {
                                type: 'input',
                                label: '邮箱',
                                prop: 'email',
                                span: 24,
                            },
                            {
                                width: 150,
                                type: 'datetime',
                                label: '创建时间',
                                prop: 'createTime',
                                format: 'YYYY-MM-DD HH:mm',
                                display: false,
                                span: 24
                            }
                        ]
                    },
                treeData: [],
                treeOption: {
                    defaultExpandAll: true,
                    addBtn: false,
                    editBtn: false,
                    delBtn: false,
                    multiple: false
                }
            }
        },
        computed: {
            isHideUserSelected: function () {
                //console.log("-------------"+JSON.stringify(this.column))
                if(!this.column){
                    return true;
                }
                return !(this.column["hideUserSelected"] ||false);
            },
            isDo: function () {
                if(!this.column){
                    return false;
                }
                return !this.column.disabled;
            },
            showSelectedBtn: function () {
                return window.isMobile;
            },
        },
        mounted(){
            if( this.getViewFormData){
                this.formData = this.getViewFormData()
            }
        },
        watch: {
            modelValue: {
                handler () {
                    if(this.modelValue && !this.selectedDataItems){
                        this.selectedDataItems = this.getDefUsers();
                    }
                }
            }
        },
        created() {
            this.myUserType = 'org';

            if(this.column) {
              this.myUserType = this.column.userType || 'org';
              if (!this.myUserType) {
                this.myUserType = 'org';
              }
              if (!this.column.onlyOrg) {
                this.column.onlyOrg = true;
              }

              this.selectedDataItems = this.getDefUsers();
              if (this.column) {
                this.multiple = this.column.multiple || this.column.multipleTest || (this.column.params && this.column.params.multiple) || false;
              }

              this.option.selection = this.multiple;
              this.option.highlightCurrentRow = !this.multiple;
              this.initData();
            }
        },
        methods: {
          toShow() {
            this.isShow = true;
          },
          getDefUsers() {
            var defKeys = [];
            var defValue = this.modelValue || this.column.value;
            //alert(JSON.stringify(defValue))
            if (defValue) {
              if (Array.isArray(defValue)) {
                defKeys = defValue;
              } else {
                defKeys = (defValue + "").split(",");
              }
            } else {
              defKeys = [];
            }
            if (defKeys.length > 0) {
              this.initUser(defKeys);
            }
          },
          nodeClickTree(data) {
            // var vs = this.$refs.tree.getCheckedKeys();
            //this.$message.success(JSON.stringify(vs))
            this.handleClearTag();

            this.searchForm.orgId = "";
            this.searchForm.roleId = "";
            if (data && data.value) {
              if (this.myUserType == "org") {
                this.searchForm.orgId = data.value;
              }
              if (this.myUserType == "role") {
                this.searchForm.orleId = data.value;
              }

            } else {
              if (this.myUserType == "org") {
                this.searchForm.orgId = null;
              }
              if (this.myUserType == "role") {
                this.searchForm.orleId = null;
              }
            }
            this.searchForm.only = this.column.onlyOrg?"2":"1";

            this.getPage();


          },
          handleCurrentRowChange(row){
            if(!row){
              return
            }
            let selection = [];
            selection.push(row)
            this.selectedDataItems = selection;
          },

          selectionChange(selection, row) {
            if(!selection){
              return
            }
            if (!this.multiple) {
              // 如果选中列表的值大于1个
              if (selection.length > 1) {
                // 将列表中的第一个元素取出
                const preVal = selection.shift();
                // 将该选项设置为未选中
                this.$refs.crud.toggleRowSelection(preVal, false);
              }
            }

            this.selectedDataItems = selection;
            // if (window.isMobile) {
            //
            // }
          },
          selectionClick(row) {
            if (!window.isMobile) {
              return
            }
            let selection = [];
            selection.push(row);
            this.selectionChange(selection, row);
            this.handleSubmit()
          },


          handleSubmit() {
            this.setSelectedData();

            this.$emit('userSelected', this.selectedDataItems);
            this.isShow = false;
          },

          handleCloseUser(tag) {
            if(!tag){
              return
            }
            let tags = _.filter(this.selectedDataItems, (user) => {
              return user.id !== tag.id
            })
            this.selectedDataItems = tags
            this.setSelectedData();
          },
          handleClearTag() {
            for (let inde=0;inde<this.selectedDataItems.length;inde++){
              this.$refs.crud.toggleRowSelection(this.selectedDataItems[inde], false);
            }
            this.selectedDataItems = []
            this.setSelectedData();
          },

          setSelectedData() {
            var vs = this.selectedDataItems;
            if (!vs || vs.length == 0) {
              if (this.formData) {
                this.formData[this.column.prop] = "";
              }
              this.selectedKey = "";
              this.$emit('update:modelValue', null);
              this.$emit('userSelected', []);
              return
            }
            let values = [];
            for (let idn = 0; idn < vs.length; idn++) {
              if (vs[idn].id === 0) {
                continue
              }
              values.push(vs[idn].id);
            }

            this.selectedKey = values.join();

            if (this.formData) {
              this.formData[this.column.prop] = this.selectedKey;
            }
            this.$emit('update:modelValue', this.selectedKey);
            this.$emit('userSelected', vs);
          },
          initData() {
            if (this.myUserType == "org") {

              fetchOrgTree().then(response => {
                this.treeData = []
                const menu = {value: 0, label: "请选择部门", children: []};
                convertDic(response.data.data.data, menu.children);
                this.treeData.push(menu);
              });
            } else if (this.myUserType == "role") {

              fetchRoleList().then(response => {
                this.treeData = []
                const menu = {value: 0, label: "请选择部门", children: []};
                convertDic(response.data.data.data, menu.children);
                this.treeData.push(menu);
              });
            }
          },
          initUser(ids) {
            let $that = this;
            getUsersByids(ids).then(response => {
              $that.selectedDataItems = response.data.data.data || [];
            });

          }
        }

    };
</script>
<style lang="scss">

.el-tag-line {
  display: block;
  margin-top: 5px;
  margin-bottom: 5px;
  font-size: 14px !important;
  padding: 2px 9px;
}

    .selected-user{
        width: 160px;
        height: 600px;
    }
    .userSelectDialog{
        width: 80vw;height: 720px;border: 0px
    }

    .userSelectDiv1{
        width: 18vw;
    }

    .userSelectDiv2{
        width: 67vw;
    }

    .selected-user{
        width: 12vw;
    }

    @media only screen and (max-width: 768px) {
        .selected-user{
            width: 0px!important;
            height:  0px!important;
            display: none;

        }
        .userSelectDialog{
            width: 100vw;height: 100vh;border: 0px
        }

        .userSelectDiv1{
            width: 30vw!important;
        }

        .userSelectDiv2{
            width: 68vw!important;
        }


    }

</style>
